<template>
  <div class="stats-view">
    <div class="stats-summary">
      <div class="stats-card">
        <div class="stats-label">本月支出</div>
        <div class="stats-value expense">{{ formatMoney(monthlyExpense) }}</div>
      </div>
      <div class="stats-card">
        <div class="stats-label">本月收入</div>
        <div class="stats-value income">{{ formatMoney(monthlyIncome) }}</div>
      </div>
    </div>

    <div class="chart-container">
      <h3>支出分类占比</h3>
      <div ref="expenseChartRef" class="chart"></div>
    </div>

    <div class="chart-container">
      <h3>收入分类占比</h3>
      <div ref="incomeChartRef" class="chart"></div>
    </div>

    <div class="chart-container">
      <h3>近7天收支趋势</h3>
      <div ref="trendChartRef" class="chart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { formatMoney } from '@/utils/format'
import { getCategoryInfo } from '@/utils/categories'

const props = defineProps({
  records: {
    type: Array,
    required: true
  }
})

const expenseChartRef = ref(null)
const incomeChartRef = ref(null)
const trendChartRef = ref(null)

let expenseChart = null
let incomeChart = null
let trendChart = null

// 本月收入和支出
const monthlyIncome = computed(() => {
  const currentMonth = new Date().toISOString().substring(0, 7)
  return props.records
    .filter(r => r.type === 'income' && r.date.substring(0, 7) === currentMonth)
    .reduce((sum, r) => sum + r.amount, 0)
})

const monthlyExpense = computed(() => {
  const currentMonth = new Date().toISOString().substring(0, 7)
  return props.records
    .filter(r => r.type === 'expense' && r.date.substring(0, 7) === currentMonth)
    .reduce((sum, r) => sum + r.amount, 0)
})

// 渲染图表
const renderCharts = () => {
  renderExpenseChart()
  renderIncomeChart()
  renderTrendChart()
}

// 支出分类图表
const renderExpenseChart = () => {
  if (!expenseChart) {
    expenseChart = echarts.init(expenseChartRef.value)
  }

  const currentMonth = new Date().toISOString().substring(0, 7)
  const expenseRecords = props.records.filter(
    r => r.type === 'expense' && r.date.substring(0, 7) === currentMonth
  )

  if (expenseRecords.length === 0) {
    expenseChart.setOption({
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center',
        textStyle: { color: '#999', fontSize: 16 }
      }
    })
    return
  }

  const categoryData = {}
  expenseRecords.forEach(record => {
    if (!categoryData[record.category]) {
      categoryData[record.category] = 0
    }
    categoryData[record.category] += record.amount
  })

  const data = Object.entries(categoryData).map(([category, amount]) => {
    const info = getCategoryInfo(category)
    return {
      name: info.icon + ' ' + info.name,
      value: amount
    }
  })

  expenseChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: ¥{c} ({d}%)'
    },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}\n¥{c}'
      },
      data: data
    }]
  })
}

// 收入分类图表
const renderIncomeChart = () => {
  if (!incomeChart) {
    incomeChart = echarts.init(incomeChartRef.value)
  }

  const currentMonth = new Date().toISOString().substring(0, 7)
  const incomeRecords = props.records.filter(
    r => r.type === 'income' && r.date.substring(0, 7) === currentMonth
  )

  if (incomeRecords.length === 0) {
    incomeChart.setOption({
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center',
        textStyle: { color: '#999', fontSize: 16 }
      }
    })
    return
  }

  const categoryData = {}
  incomeRecords.forEach(record => {
    if (!categoryData[record.category]) {
      categoryData[record.category] = 0
    }
    categoryData[record.category] += record.amount
  })

  const data = Object.entries(categoryData).map(([category, amount]) => {
    const info = getCategoryInfo(category)
    return {
      name: info.icon + ' ' + info.name,
      value: amount
    }
  })

  incomeChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: ¥{c} ({d}%)'
    },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}\n¥{c}'
      },
      data: data,
      color: ['#10b981', '#34d399', '#6ee7b7', '#a7f3d0', '#d1fae5']
    }]
  })
}

// 趋势图表
const renderTrendChart = () => {
  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value)
  }

  const dates = []
  const expenseData = []
  const incomeData = []

  for (let i = 6; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    const dateStr = date.toISOString().split('T')[0]
    dates.push(date.getMonth() + 1 + '/' + date.getDate())

    const dayExpense = props.records
      .filter(r => r.type === 'expense' && r.date === dateStr)
      .reduce((sum, r) => sum + r.amount, 0)

    const dayIncome = props.records
      .filter(r => r.type === 'income' && r.date === dateStr)
      .reduce((sum, r) => sum + r.amount, 0)

    expenseData.push(dayExpense)
    incomeData.push(dayIncome)
  }

  trendChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: ['支出', '收入']
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '支出',
        type: 'bar',
        data: expenseData,
        itemStyle: { color: '#ef4444' }
      },
      {
        name: '收入',
        type: 'bar',
        data: incomeData,
        itemStyle: { color: '#10b981' }
      }
    ]
  })
}

onMounted(() => {
  renderCharts()
})

watch(() => props.records, () => {
  renderCharts()
}, { deep: true })
</script>

<style scoped>
.stats-summary {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.stats-card {
  padding: 20px;
  background: var(--bg-color);
  border-radius: 10px;
  text-align: center;
}

.stats-label {
  font-size: 0.9rem;
  color: var(--text-secondary);
  margin-bottom: 8px;
}

.stats-value {
  font-size: 1.8rem;
  font-weight: bold;
}

.stats-value.expense {
  color: var(--danger-color);
}

.stats-value.income {
  color: var(--success-color);
}

.chart-container {
  margin-bottom: 24px;
}

.chart-container h3 {
  margin-bottom: 16px;
  color: var(--text-primary);
}

.chart {
  width: 100%;
  height: 300px;
}

@media (max-width: 640px) {
  .stats-summary {
    grid-template-columns: 1fr;
  }
}
</style>
